<?php

class User_accounts_model extends CI_Model {

	function __construct() {
		parent::__construct();
		$this->load->helper('date');
	}

	var $table_name = 'user_account';
	var $primary_key = 'email';
	var $display_field = '';
	var $_foreign_keys = array(
			// 'MaLop' => array('Lop_model', 'MaLop'),
	);

	/**
	 *
	*/
	function _connect($email, $password) {

		$row = array();

		if (!empty($email) AND !empty($password)) {
			$this->db->where('email', $email);
			$this->db->where('password', $password);
			$rows = $this->db->get($this->table_name)->result_array();
			if(!empty($rows)){
				$row = $rows[0]; // return row object
			}
		}

		return $row;
	}

	function add($data = array()){
		$this->db->insert('user_account', array('email'=> $data['email'], 'password'=> $data['passwd'], 'last_login'=> gmt_to_local(now(), 'UP7', TRUE)));
		//$this->_insert_rows(, 'user_account');
	}

	function _check_user_exist($email){
		if (!empty($email)) {
			$this->db->where('email', $email);
			$rows = $this->db->get($this->table_name)->result_array();
			if(!empty($rows)){
				return true;
			}
			return false;
		}
	}

	function get_ip_address() {
		foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
			if (array_key_exists($key, $_SERVER) === true) {
				foreach (explode(',', $_SERVER[$key]) as $ip) {
					if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
						return $ip;
					}
				}
			}
		}
	}


	function _save_session($user) {
		$user['last_login'] = date("Y-m-d H:i:s");

		if(isset($user['user_id'])){ // Remove PRIMARY_KEY
			unset($user['user_id']);
		}
		//$user['uacc_ip_address'] = $this->get_ip_address();
		$this->_update_row($user);
	}
}